<template>
	<nt-container bg-color="#fff">
		<nt-grid :data="entryList" @click="toPage"></nt-grid>
		<view class="nt-submit">
			<view class="nt-submit-item border pad_lr">
				<nt-title label="成本内容">
					<template #right>
						<view class="cost">总成本：{{finalCost || 0}}</view>
					</template>
				</nt-title>
			</view>
			<view class="nt-submit-item border pad">
				<view class="nt-submit-item__type">
					<view class="nt-submit-item__type--label">配件种类</view>
					<view class="nt-submit-item__type--list">
						<view 
							class="nt-submit-item__type--item"
							:class="{ company: it.value == 1, self: it.value == 2, procure: it.value == 3 }"
							v-for="it in partsTypeList" :key="it.value" @tap="addParts(it.value)">{{it.label}}</view>
					</view>
				</view>
			</view>
			<view class="parts-list">
				<view class="parts-list__item" 
					v-for="(it, index) in allPartsList" 
					:class="{ company: it.type == 1, self: it.type == 2, procure: it.type == 3 }"
					:key="index"
				>
					<view class="parts-list__item--content">
						<view 
							class="parts-list__item--content-type" 
							@tap="selectParts(it.type, index)"
						>{{ it.type == 1 ? '公司配件' : it.type == 2 ? '采购配件' : '个人配件' }}</view>
						<view class="parts-list__item--content-name" :class="{ empty: !it.name }">{{ it.name || '名称' }}</view>
						<view class="parts-list__item--content-number" :class="{ empty: !it.quantity }">{{ it.quantity || '数量' }}</view>
						<view class="parts-list__item--content-price" :class="{ empty: !it.price }">
							<u--input v-model="it.price" placeholder="价格" :readonly="it.type != 2"></u--input>
						</view>
					</view>
					<view class="parts-list__item--btn"  @tap="deleteParts(index)">-</view>
				</view>
			</view>
			
			<view class="nt-submit-item border pad_lr" v-if="showProcureUpload">
				<nt-title label="上传采购图片">
					<template #right>
						<view class="tip">每张图片大小不能超过1M</view>
					</template>
				</nt-title>
				<div class="nt-submit-item__procure">
					<nt-upload :max-count="9" @success="procureImage = $event" :images="orderInfo.purchase_images"></nt-upload>
				</div>
			</view>
			
			<view class="nt-submit-footer">
				<nt-button text="保存录入详情" @click="submit"></nt-button>
			</view>
		</view>
		<u-calendar :show="show" @close="show = false" @confirm="confirm" closeOnClickOverlay></u-calendar>
		<u-picker 
			:show="showParts" 
			ref="uPicker" 
			:columns="columns" 
			keyName="name" 
			@confirm="confrimParts"
			@close="showParts = false" 
			@cancel="showParts = false" 
			closeOnClickOverlay
		 ></u-picker>
		 <u-picker
		 	:show="showProcureParts" 
		 	ref="uPicker" 
		 	:columns="procureColumns" 
		 	keyName="name" 
		 	@confirm="confrimParts"
		 	@close="showProcureParts = false" 
		 	@cancel="showProcureParts = false" 
		 	@change="changeHandler"
		 	closeOnClickOverlay
		  ></u-picker>
		<u-picker 
			:show="showBackParts" ref="backPartsRef" 
			:columns="[formConfig.takebackTypeList]" 
			keyName="name" 
			@confirm="confrimBackParts" 
			@close="showBackParts = false" 
			@cancel="showBackParts = false" 
			closeOnClickOverlay
		></u-picker>
		
		<nt-order-more :show="showMore"  @close="showMore = $event" :auth="orderInfo.powerStatus" :id="orderInfo.id" :is_submit="orderInfo.is_submit"></nt-order-more>
		<u-picker :show="showInvoice" :columns="[formConfig.invoiceHistoryList]" keyName="name" @cancel="showInvoice = false" @confirm="confirmInvoice" @close="showInvoice = false" closeOnClickOverlay></u-picker>
	</nt-container>
</template>

<script>
import { nav, transTree } from "@/utils"
import { getCommonFormConfig, orderDetailSumit, getOrderDetail } from "@/api"
import { appConfig } from "@/config"
export default {
	data() {
		return {
			partsTypeList:[
				{ label: "公司配件", value: 1 },
				{ label: "采购配件", value: 2 },
				{ label: "个人配件", value: 3 },
			],
			partsType: 1,
			entryList: [
				{ label: "验券", icon: "/static/image/yanquan.png", url: '/subpackage/order/pages/check-ticket/index' },
				{ label: "支付提交", icon: "/static/image/yanquan.png", url: '/subpackage/order/pages/payment/index' },
				{ label: "历史记录", icon: "/static/image/history.png" },
				{ label: "更多功能", icon: "/static/image/more.png", url: "", type: "more" },
			],
			show: false,
			showMore: false,
			selectDate: '',
			orderId: "",
			orderInfo: {},
			// 配件list
			allPartsList: [],
			// 带回配件
			backPartsList: [
				{ value: "", name: "", quantity: 1, price: 0 }
			],
			// 配件信息
			parts: {
				// 公司配件
				company: [],
				// 个人配件
				self: []
			},
			// 发票信息
			invoiceInfo: {
				remarks: "",
				price: ""
			},
			// 历史发票
			invoiceHistoryList: [],
			columns: [],
			procureColumns: [],
			formConfig: {},
			showParts: false,
			showProcureParts: false,
			// 当前选择的配件类型
			currentParts: {
				index: 0,
				type: 0
			},
			// 客户类型
			customType: "",
			// 评价
			evaluate: "",
			evaluateImage: [],
			currentBackPartsIndex: 0,
			showBackParts: false,
			// 采购图片
			procureImage: [],
			// 历史发票
			showInvoice: false,
		}
	},
	computed: {
		// 总成本 = 单费 + 配件费用 + 带回配件费用 + 税费
		finalCost(){
			// 配件成本
			const partsCost = this.allPartsList.reduce((acc, item) => acc += item.quantity * item.price, 0)
			// 带回成本
			const backPartsCost = this.backPartsList.reduce((acc, item) => acc += item.quantity * item.price, 0)
			// 税费
			// const taxation = this.invoiceInfo.price * appConfig.taxation
			
			return partsCost + backPartsCost
		},
		// 税费
		tax(){
			const price = this.formConfig.tax * this.invoiceInfo.price;
			if(isNaN(price) || price <= 0) return ""
			return price
		},
		showProcureUpload(){
			return this.allPartsList.some(item => item.type == 2)
		}
	},
	onLoad(options){
		this.orderId = options.id
		this.getFormConfig()
		this.getDetail()
	},
	methods: {
		toPage(index){
			const data = this.entryList[index]
			if(!data.url && data.type === 'more'){
				this.showMore = true
				return;
			}
			this.nav(`${data.url}?id=${this.orderId}`)
		},
		confirm(e){
			console.log(e)
			this.show = false;
			this.selectDate = e[0]
		},
		// 选择发票
		confirmInvoice(e){
			console.log(e)
			this.invoiceInfo.remarks = e.value[0].value
			this.showInvoice = false
		},
		// 选择配件
		selectParts(type, index){
			this.partsType = type
			this.currentParts = { index, type }
			const pickerRef = this.$refs.uPicker
			if(type == 1){
				this.showParts = true
				this.columns = [this.formConfig.partsCompanyList]
			}else if(type == 3){
				this.showParts = true
				this.columns = [this.formConfig.partsPersonList]
			}else {
				this.showProcureParts = true
				const tree = transTree(this.formConfig.partsPurchaseTypeList)
				this.procureColumns = [transTree(this.formConfig.partsPurchaseTypeList)]
				this.$set(this.procureColumns, this.procureColumns.length, tree[0].children)
			}
		},
		// 删除配件信息
		deleteParts(index){
			console.log(index)
			this.allPartsList.splice(index, 1)
		},
		// 添加配件信息
		addParts(type){
			let tpl = {
				id: "",
				name: "",
				quantity: "",
				price: "",
				type
			}
			this.$set(this.allPartsList, this.allPartsList.length, tpl)
		},
		confrimParts(e){
			const { type, index } = this.currentParts
			let value = e.value[0]
			if(e.value.length > 1){
				value = e.value[1]
			}
			this.allPartsList[index].name = value.name
			this.allPartsList[index].quantity = 1
			this.allPartsList[index].id = value.value
			this.allPartsList[index].price = value.price ?? 0
			this.allPartsList[index].purchaseType = value.type
			this.showParts = false
			this.showProcureParts = false
		},
		// 二级选择
		changeHandler(e){
			const pickerRef = this.$refs.uPicker
			if(e.columnIndex === 0){
				if(this.procureColumns[0][e.index].children){
					const tree = transTree(this.formConfig.partsPurchaseTypeList)
					// console.log(tree)
					this.$set(this.procureColumns, 1, this.procureColumns[0][e.index].children)
					// pickerRef.setColumnValues(1, tree[e.index].children)
				}
			}
		},
		
		// 选择带回配件
		selectBackParts(index){
			this.showBackParts = true
			this.currentBackPartsIndex = index
		},
		// 删除带回配件
		deleteBackParts(index){
			this.backPartsList.splice(index, 1)
		},
		// 添加带回配件
		addBackParts(){
			let tpl = {
				value: "",
				name: "",
				quantity: 1,
				price: 0
			}
			this.$set(this.backPartsList, this.backPartsList.length, tpl)
		},
		confrimBackParts(e){
			let value = e.value[0]
			let index = this.currentBackPartsIndex
			this.backPartsList[index].value = value.value
			this.backPartsList[index].name = value.name
			this.backPartsList[index].quantity = 1
			this.backPartsList[index].price = value.price
			this.showBackParts = false
			
		},
		// 获取配件
		getFormConfig(type){
			getCommonFormConfig(this.orderId).then(res => {
				console.log(res,'获取配件')
				const { code, data } = res;
				if(code !== 1) return;
				this.formConfig = data
			})
		},
		// 提交详情参数格式化
		formatParams(){
			// let isTakeback = this.backPartsList.every(item => item.)
			return {
				// 订单ID
				realorder_id: this.orderId,
				// 公司配件ID
				company: this.allPartsList.filter(item => item.type == 1).map(it => {
					return { 
						parts_person_id: it.id, 
						number: it.quantity
					}
				}),
				// 个人配件
				person: this.allPartsList.filter(item => item.type == 3).map(it => {
					return {
						parts_person_id: it.id, 
						number: it.quantity
					}
				}),
				// 采购配件
				purchase: this.allPartsList.filter(item => item.type == 2).map(it => {
					return 	{
						type: it.purchaseType,
						content: it.id,
						price: it.price
					}
					
				}),
				// 保修日期
				warranty_date: this.selectDate,
				// 好评类型
				is_praise: this.evaluate,
				// 发票内容
				invoice_content: this.invoiceInfo.remarks,
				//税费
				postage: this.invoiceInfo.price * this.formConfig.tax,
				// 好评
				hp_img: this.evaluateImage.map(item => item.url)[0] || "",
				// 配件报销
				purchase_images: this.procureImage.map(item => item.url),
				// 带回配件
				takeback: this.backPartsList.map(item => {
					return {
						takeback_parts_type: item.value,
						takeback_parts_name: item.name,
						takeback_number: item.quantity,
						takeback_parts_price: item.price
					}
				}),
				utype_tags: this.customType
				
			}
		},
		submit(){
			const { remarks, price } = this.invoiceInfo
			if(!remarks) return this.toast("发票内容不能为空")
			if(!price) return this.toast("请输入发票金额")
			const formData = this.formatParams()
			console.log(formData)
			orderDetailSumit(formData).then(res => {
				console.log(res,'详情提交')
				if(res.code === 1){
					this.toast("提交成功")
					setTimeout(() => this.back(), 1000)
				}
			})
		},
		// 订单详情
		getDetail(){
			getOrderDetail(this.orderId).then(res => {
				const { data, code } = res;
				this.orderInfo = data;
				this.paymentList = (data.payment || []).map(item => {
					return {
						paytype: item.paytype,
						payprice: item.payprice
					}
				})
				this.entryList = [
					{ label: "验券", icon: "/static/image/yanquan.png", url: '/subpackage/order/pages/check-ticket/index', visiable: data.powerStatus.postPayment === 1  },
					{ label: "支付提交", icon: "/static/image/yanquan.png", url: '/subpackage/order/pages/payment/index', visiable: data.powerStatus.postPayment === 1 },
					{ label: "历史记录", icon: "/static/image/history.png", url: '/subpackage/order/pages/history/index', visiable: true },
					{ label: "更多功能", icon: "/static/image/more.png", url: "", type: "more", visiable: true }
				]
				this.echoData(data)
			})
		},
		// 选择历史发票
		selectHistoryInvoice(){
			if(!this.formConfig.invoiceHistoryList.length) return this.toast("暂无历史发票选择")
			this.showInvoice = true;
		},
		// 数据回显
		echoData(data){
			const { invoice, purchase_images, warranty_date, praise_type_text, takeback, partsperson, utype_tags, partscompany } = data;
			this.invoiceInfo.remarks = invoice.invoice_content
			this.invoiceInfo.price = invoice.postage
			this.selectDate = warranty_date
			const evaluateFind = this.formConfig.praiseTypeList.find(it => it.name === praise_type_text)
			if(evaluateFind){
				this.evaluate  = evaluateFind.value
			}
			this.backPartsList = takeback.map(item => {
				return {
					value: item.takeback_parts_type,
					name: item.takeback_parts_name,
					quantity: item.takeback_number,
					price: item.takeback_parts_price
				}
			})
			// 个人配件
			const p = []
			partsperson.map(item => {
				let list = this.formConfig.partsPersonList
				for(let i =0;i < list.length;i++){
					if(item.parts_person_id === list[i].value){
						p.push({
							id: list[i].value,
							name: list[i].name,
							price: list[i].price,
							quantity: item.number,
							type: 3
						})
					}
				}
			})
			// 公司配件
			const c = []
			// 采购
			const cg = []
			partscompany.map(item => {
				let list = this.formConfig.partsCompanyList
				if(item.is_new === 1){
					cg.push({
						id: item.content,
						name: item.parts_name,
						price: item.price,
						quantity: 1,
						type: 2
					})
				}
				for(let i =0;i < list.length;i++){
					if(item.parts_person_id === list[i].value){
						c.push({
							id: list[i].value,
							name: list[i].name,
							price: list[i].price,
							quantity: item.number,
							type: 1
						})
					}
				}
			})
			
			this.allPartsList = [...p, ...c,...cg]
			this.customType = utype_tags || ""
			console.log(this.allPartsList,'---this.allPartsList')
			// backPartsList: [
			// 	{ value: "", name: "", quantity: 1, price: 0 }
			// ],
		}
	}
}
</script>

<style lang="scss" scoped>
$compay: #E5ECFF;
$self: #FBEEE8;
$procure: #E0F7FF;
$compay-color: #435BA1;
$self-color: #9B583D;
$procure-color: #366F83;
.nt-submit{
	padding: 0 0 150rpx;
	box-sizing: border-box;
	overflow-x: hidden;
	/deep/ .plan-class{
		font-size: 26rpx;
		color:#666;
	}
	/deep/ .nt-title{
		position: relative;
	}
	.cost, .tip{
		position: absolute;
		right: 0;
		top: 50%;
		transform: translateY(-50%);
		
	}
	.cost{
		font-weight: bold;
		color: var(--theme-color);
		font-size: 32rpx;
	}
	.tip{
		font-size: 24rpx;
		color: #aaa;
	}
	.gap{
		height: 10rpx;
		background: #F2F4F6;
	}
	
	.company{
		background: $compay ;
		color: $compay-color;
		&::after{
			background: $compay-color;
		}
	}
	.self{
		background: $self;
		color: $self-color;
		&::after{
			background: $self-color;
		}
	}
	.procure{
		background: $procure;
		color: $procure-color;
		&::after{
			background: $procure-color;
		}
	}
	.btn{
		width: 30rpx;
		height: 30rpx;
		line-height: 30rpx;
		font-size: 30rpx;
		font-weight: bold;
		color:#fff;
		border-radius: 50%;
		text-align:center;
		&.add{
			background: var(--theme-color)
		}
		&.reduce{
			background: #333333;
		}
	}
	.back{
		&-list{
			&__item{
				display:flex;
				align-items: center;
				justify-content: space-between;
				font-size: 28rpx;
				padding: 15rpx 10rpx;
				box-sizing: border-box;
				color:#666;
				text-align: center;
				.weight{
					font-weight: bold;
					color:#333;
				}
				&--type{
					width: 150rpx;
				}
				&--name{
					flex: 1;
				}
				&--number{
					width: 160rpx;
				}
				&--price{
					width: 160rpx;
					/deep/.u-input{
						border: none !important;
						padding: 0 !important;
					}
				}
				&--btn{
					width: 60rpx;
					&-b, &-r{
						width: 40rpx;
						height: 40rpx;
						line-height: 40rpx;
						border-radius: 50%;
						text-align: center;
						font-size: 40rpx;
						font-weight: bold;
						color:#fff;
						
					}
					&-b{
						background: var(--theme-color);
					}
					&-r{
						background: #333;
					}
				}
				
			}
		}
	}
	.parts{
		&-list{
			&__item{
				display:flex;
				align-items: center;
				justify-content: space-between;
				height: 80rpx;
				padding: 0 20rpx;
				&--content{
					height: 56rpx;
					background:#fff;
					border-radius: 10rpx;
					flex: 1;
					display:flex;
					align-items: center;
					padding: 0 20rpx;
					box-sizing: border-box;
					font-size: 28rpx;
					.empty{
						color:#999
					}
					/deep/ .u-input{
						border:none !important;
						padding: 0 !important;
						text-align: center !important;
					}
					&-type{
						// width: 100rpx;
						flex: 1;
						color:#333;
					}
					&-name{
						// width: 100rpx;
						flex: 1;
					}
					&-number{
						width: 100rpx;
					}
					&-price{
						width: 100rpx;
						text-align: center;
					}
				}
				&--btn{
					width:40rpx;
					height: 40rpx;
					line-height: 40rpx;
					margin-left: 20rpx;
					border-radius: 50%;
					background:#333;
					text-align: center;
					font-weight: bold;
					color:#fff;
				}
			}
		}
	}
	&-item{
		&.parts{
			padding: 0 20rpx;
			margin: 0 -20rpx;
		}
		&.border{
			border-bottom: 1rpx solid #eee;
		}
		&.pad_lr{
			padding: 0 20rpx;
		}
		&.pad_tb{
			padding: 25rpx 0
		}
		&.pad{
			padding: 25rpx;
		}
		&.flex{
			display:flex;
			align-items: center;
			
		}
		&__table{
			display: table;
			width: 100%	
		}
		&__row{
			display:flex;
			justify-content: space-between;
			align-items: center;
			&.pad_lr{
				padding: 0 20rpx;
			}
		}
		&__body{
			// display: table-column-group;
		}
		&__cell{
			// display: table-cell;
			flex: auto;
			text-align: left;
			padding: 20rpx 2rpx;
			font-size: 20rpx;
			color: #ccc;
			&.weight{
				color:#333;
				font-weight: bold;
			}
		}
		&__cell1{
			width: 230rpx;
		}
		&__cell2{
			width: 80rpx;
			text-align: right;
		}
		&__label{
			width: 200rpx;
			white-space: nowrap;
			color: #333;
			font-size: 28rpx;
		}
		&__type{
			color: #333;
			&--label{
				font-size: 24rpx;
			}
			&--list{
				display:flex;
				align-items: center;
				justify-content: space-between;
				margin-top: 20rpx;
			}
			&--item{
				width: 200rpx;
				height: 70rpx;
				border-radius: 10rpx;
				font-size: 24rpx;
				display:flex;
				align-items: center;
				justify-content: center;
				font-weight: bold;
				&::after{
					content: "+";
					border-radius: 50%;
					text-align: center;
					color:#fff;
					display:flex;
					align-items: center;
					justify-content: center;
					width: 30rpx;
					height: 30rpx;
					margin-left: 10rpx;
					color:#fff;
					font-weight: bold;
					font-size: 30rpx;
				}
			}
		}
		&__procure{
			display:flex;
			align-items: center;
		}
		&__content{
			flex: 1;
			/deep/ .u-radio {
				&__text{
					color: #333;
					font-size: 28rpx;
				}
				& + .u-radio{
					margin-left: 90rpx;
				}
			}
			&--select{
				font-size: 28rpx;
				color: #ccc;
			}
		}
		&__invoice{
			flex: 1;
			color: #333;
			font-size: 28rpx;
			margin-bottom:  20rpx;
			min-height: 65rpx;
			&.flex{
				display: flex;
				justify-content: space-between;
				align-items: center;
			}
			&--input{
				margin-top: 20rpx;
				flex: 1;
				&.no-margin{
					margin: 0;
				}
			}
			&--desc{
				font-size: 20rpx;
				color:#999;
			}
			&--label{
				font-size: 30rpx;
				color:#333;
				&.width_150{
					width: 150rpx;
				}
				text{
					color:#f00;
				}
			}
			input{
				width: 300rpx;
				height: 65rpx;
				border-radius: 10rpx;
				border:1rpx solid #ccc;
				padding: 0 20rpx;
				box-sizing: border-box;
			}
			/deep/ .placeholder-class{
				font-size: 24rpx;
				color: #aaa;
			}
			/deep/ .u-textarea{
				background: #F2F4F6
			}
		}
		&__evaluate{
			&--list{
				display: flex;
				justify-content: space-between;
				flex-wrap: wrap;
			}
			&--item{
				width: 48%;
				margin-bottom: 20rpx;
				border-radius: 10rpx;
				border: 1rpx solid #CCCCCC;
				display:flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				box-sizing: border-box;
				height: 120rpx;
				color: #333;
				&.active{
					color:#fff;
					background: var(--theme-color);
					color: #fff;
				}
				&--item:nth-child(2n){
					margin-left: 4%;
				}
				&-title{
					font-size: 24rpx;
					font-weight: bold;
				}
				&-desc{
					font-size: 20rpx;
					margin-top: 10rpx;
				}
			}
		}
		&__upload{
			padding: 40rpx 10rpx;
			box-shadow: 0 0 10rpx rgba(0,0,0,0.1);
			&--title{
				font-size: 24rpx;
				color: #aaa;
				margin-bottom: 20rpx;
				text{
					color: var(--theme-color)
				}
			}
		}
		&__header &__cell{
			font-weight: bold;
			color:#333;
			font-size: 24rpx;
		}
	}
	&-footer{
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 130rpx;
		background:#fff;
		padding: 0 70rpx;
		box-sizing: border-box;
		display:flex;
		align-items: center;
		/deep/ .button-container{
			width: 100%;
		}
	}
}
</style>